<template>
  <div class="cashier">
    <el-row :gutter="20">
      <!-- 左侧：商品选择 -->
      <el-col :span="14">
        <el-card>
          <template #header>
            <div class="search-bar">
              <el-input
                v-model="searchKeyword"
                placeholder="扫码或输入商品名称/拼音首字母"
                clearable
                @keyup.enter="searchProduct"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="searchProduct">搜索</el-button>
            </div>
          </template>
          
          <!-- 分类快速选择 -->
          <div class="category-bar">
            <el-tag
              :type="selectedCategory === null ? 'primary' : 'info'"
              class="category-tag"
              @click="selectCategory(null)"
            >
              全部
            </el-tag>
            <el-tag
              v-for="category in categories"
              :key="category.id"
              :type="selectedCategory === category.id ? 'primary' : 'info'"
              class="category-tag"
              @click="selectCategory(category.id)"
            >
              {{ category.icon || '📦' }} {{ category.name }}
            </el-tag>
          </div>
          
          <div class="product-grid">
            <div
              v-for="product in products"
              :key="product.id"
              class="product-item"
              @click="addToCart(product)"
            >
              <div class="product-image">
                <img :src="getImageUrl(product.image)" :alt="product.name" />
              </div>
              <div class="product-category">{{ product.categoryIcon || '📦' }} {{ product.categoryName || '未分类' }}</div>
              <div class="product-name">{{ product.name }}</div>
              <div class="product-price">¥{{ product.price }}</div>
              <div class="product-stock">库存: {{ product.stock }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧：购物车和结算 -->
      <el-col :span="10">
        <el-card class="cart-card">
          <template #header>
            <div class="card-header">
              <span>购物车</span>
              <el-button v-if="cartItems.length > 0" text type="danger" @click="clearCart">
                清空
              </el-button>
            </div>
          </template>
          
          <div class="cart-list">
            <div v-for="(item, index) in cartItems" :key="index" class="cart-item">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-price">¥{{ item.price }}</div>
              </div>
              <div class="item-actions">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.stock"
                  size="small"
                  @change="updateTotal"
                />
                <el-button
                  type="danger"
                  text
                  :icon="Delete"
                  @click="removeItem(index)"
                />
              </div>
            </div>
            
            <el-empty v-if="cartItems.length === 0" description="购物车为空" :image-size="100" />
          </div>
          
          <div v-if="cartItems.length > 0" class="cart-footer">
            <div class="total-info">
              <div class="info-row">
                <span>商品数量：</span>
                <span class="value">{{ totalQuantity }} 件</span>
              </div>
              <div class="info-row total">
                <span>合计：</span>
                <span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
              </div>
            </div>
            
            <div class="payment-methods">
              <el-radio-group v-model="paymentMethod">
                <el-radio-button value="cash">现金</el-radio-button>
                <el-radio-button value="alipay">支付宝</el-radio-button>
                <el-radio-button value="wechat">微信</el-radio-button>
              </el-radio-group>
            </div>
            
            <el-button
              type="primary"
              size="large"
              style="width: 100%"
              :loading="settling"
              @click="handleSettle"
            >
              结算
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { searchProduct as searchProductApi, getProductList } from '@/api/product'
import { getCategoryList } from '@/api/category'
import { createCashierOrder } from '@/api/cashier'
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const searchKeyword = ref('')
const selectedCategory = ref(null)
const products = ref([])
const categories = ref([])
const cartItems = ref([])
const paymentMethod = ref('cash')
const settling = ref(false)

onMounted(() => {
  loadCategories()
  loadProducts()
})

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      // 只显示启用状态的分类
      categories.value = res.data.filter(cat => cat.status === 1)
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  searchKeyword.value = ''  // 清空搜索
  loadProducts()
}

const loadProducts = async () => {
  try {
    const requestData = {
      page: 1,
      pageSize: 50,
      status: 1,  // 只查询上架商品
      categoryId: selectedCategory.value || null,
      name: searchKeyword.value || null
    }
    
    const res = await getProductList(requestData)
    if (res.code === 200 && res.data) {
      products.value = res.data.records || []
      
      // 添加分类图标
      products.value = products.value.map(product => {
        const category = categories.value.find(cat => cat.id === product.categoryId)
        return {
          ...product,
          categoryIcon: category?.icon || '📦'
        }
      })
    }
  } catch (error) {
    console.error('加载商品失败:', error)
    // 使用模拟数据
    products.value = Array.from({ length: 20 }, (_, i) => ({
      id: i + 1,
      name: `商品${i + 1}`,
      categoryName: ['饮料', '零食', '日用品'][i % 3],
      categoryIcon: ['🥤', '🍭', '🧹'][i % 3],
      price: (Math.random() * 50 + 5).toFixed(2),
      image: 'https://via.placeholder.com/100',
      stock: Math.floor(Math.random() * 100) + 10
    }))
  }
}

const searchProduct = async () => {
  selectedCategory.value = null  // 清空分类筛选
  loadProducts()
}

const addToCart = (product) => {
  if (product.stock === 0) {
    ElMessage.warning('商品已售罄')
    return
  }
  
  const existItem = cartItems.value.find(item => item.id === product.id)
  if (existItem) {
    if (existItem.quantity < product.stock) {
      existItem.quantity++
    } else {
      ElMessage.warning('库存不足')
    }
  } else {
    cartItems.value.push({
      ...product,
      quantity: 1
    })
  }
}

const removeItem = (index) => {
  cartItems.value.splice(index, 1)
}

const clearCart = () => {
  cartItems.value = []
}

// 获取图片URL（处理相对路径和绝对路径）
const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/100'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return 'http://localhost:8080' + url
}

const totalQuantity = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
})

const totalAmount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

const updateTotal = () => {
  // 触发计算属性更新
}

const handleSettle = async () => {
  settling.value = true
  try {
    const orderData = {
      items: cartItems.value.map(item => ({
        productId: item.id,
        quantity: item.quantity,
        price: item.price
      })),
      totalAmount: totalAmount.value,
      paymentMethod: paymentMethod.value
    }
    
    const res = await createCashierOrder(orderData)
    
    if (res.code === 200) {
      ElMessage.success('结算成功')
      clearCart()
    } else {
      ElMessage.error(res.message || '结算失败')
    }
  } catch (error) {
    console.error('结算失败:', error)
    ElMessage.error(error.message || '结算失败')
  } finally {
    settling.value = false
  }
}
</script>

<style lang="scss" scoped>
.cashier {
  .search-bar {
    display: flex;
    gap: 10px;
  }
  
  .category-bar {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 15px;
    
    .category-tag {
      cursor: pointer;
      padding: 8px 16px;
      font-size: 14px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      }
    }
  }
  
  .product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 15px;
    max-height: calc(100vh - 250px);
    overflow-y: auto;
    
    .product-item {
      border: 1px solid #e8e8e8;
      border-radius: 8px;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      }
      
      .product-image {
        width: 100%;
        height: 80px;
        margin-bottom: 8px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 4px;
        }
      }
      
      .product-category {
        font-size: 12px;
        color: #909399;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .product-name {
        font-size: 14px;
        margin-bottom: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .product-price {
        color: #ff4d4f;
        font-weight: bold;
        margin-bottom: 3px;
      }
      
      .product-stock {
        font-size: 12px;
        color: #999;
      }
    }
  }
  
  .cart-card {
    height: calc(100vh - 160px);
    display: flex;
    flex-direction: column;
    
    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: bold;
    }
    
    .cart-list {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;
      
      .cart-item {
        display: flex;
        justify-content: space-between;
        padding: 12px;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .item-info {
          flex: 1;
          
          .item-name {
            font-size: 14px;
            margin-bottom: 5px;
          }
          
          .item-price {
            color: #ff4d4f;
            font-weight: bold;
          }
        }
        
        .item-actions {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }
    }
    
    .cart-footer {
      border-top: 2px solid #f0f0f0;
      padding-top: 15px;
      
      .total-info {
        margin-bottom: 15px;
        
        .info-row {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          
          &.total {
            font-size: 18px;
            font-weight: bold;
            
            .amount {
              color: #ff4d4f;
              font-size: 24px;
            }
          }
        }
      }
      
      .payment-methods {
        margin-bottom: 15px;
        
        :deep(.el-radio-group) {
          display: flex;
          width: 100%;
          
          .el-radio-button {
            flex: 1;
            
            .el-radio-button__inner {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style>












